<?php 
/**
 *  acces_token api 
 */

namespace Api\Controller;
use Api\Controller\VerifyController;
class TokenController extends VerifyController{
	private $token;
	private $password;
    
    public function _initialize(){
		parent::_initialize();
	}
	
	/** 
	 * 短信登录 
	 */
	public function smsLogin(){
		$mobileNum=trim(I("mobileNum"));
		$smsCode=trim(I("smsCode"));
		
		$data=array(
			"mobileNum"=>$mobileNum,
			"smsCode"=>$smsCode
		);
		
		if (!isNotEmptyArr($data)) {
			$this->_returnJson(array("result"=>0,"info"=>"empty mobileNum or empty smsCode","code"=>"101"));
		}
		
		//获取接口数据
		$result=$this->_loginSms($mobileNum, $smsCode);
		
		if (!$result) {
			$this->_returnJson(array("result"=>0,"info"=>"api return error","errorMsg"=>$this->apiErrorMsg,"code"=>"119") );
		}
		
		$token=$result['token'];
		$this->token=$result['token'];
		$result['expireIn']!="-1"?$expire=$result['expireIn']:$expire=0;
		
		$this->_loginAction($mobileNum, $this->_creatToken(), $expire);
	}
	
	/**
	 *  账号密码登录 
	 */
	public function login(){
		
		$mobileNum=trim(I("mobileNum"));
		$password=trim(I("password"));
		$data=array(
				"mobileNum"=>$mobileNum,
				"password"=>$password
		);
		//file_put_contents("log/pwd.txt", $password,FILE_APPEND);
		if (!isNotEmptyArr($data)) {
			$this->_returnJson(array("result"=>0,"info"=>"empty mobileNum or empty password","code"=>"101") );
		}
				
		$result=$this->_loginPassword($data['mobileNum'],$data['password']);
		
		if (!$result) {
			$this->_returnJson(array("result"=>0,"info"=>"api return error","errorMsg"=>$this->apiErrorMsg,"code"=>"119") );
		}
		
		$token=$result['token'];
		$this->token=$token;
		$this->password=$data['password'];
		
		$result['expireIn']!="-1"?$expire=$result['expireIn']:$expire=0;
	
		$this->_loginAction($mobileNum, $this->_creatToken(), $expire);
	}
	
	/**
	 *  请求发送验证短信操作
	 */
	public function getMsmCode(){
		
		empty($_POST['mobileNum'])?$this->_returnJson(array("result"=>0,"info"=>"empty moblieNum","code"=>101)):$mobileNum=I("post.mobileNum");
	    //empty($_GET['mobileNum'])?$this->_returnJson(array("result"=>0,"info"=>"empty moblieNum","code"=>101)):$mobileNum=I("get.mobileNum");
		$result=$this->_sendSmsCode($mobileNum);
		if (!$result) {
			$this->_returnJson(array("result"=>0,"info"=>"api return error","errorMsg"=>$this->apiErrorMsg,"code"=>"119") );
		}
		
		$this->_returnJson(array("result"=>1));
	}
	
	/**
	 *  用户注册操作
	 */
	public function register(){
		
		$data=array(
			"mobileNum"=>I("post.mobileNum"),
			"smsCode"=>I("post.smsCode"),
			"password"=>I("post.password"),
		);
		
		!isNotEmptyArr($data)?$this->_returnJson(array("result"=>0,"info"=>"empty moblieNum","code"=>101)):"";
		
		$result=$this->_register($data['mobileNum'],$data['smsCode'],$data['password']);
		//var_dump($result);exit;
		if (!$result) {
			$this->_returnJson(array("result"=>0,"info"=>"api return error","errorMsg"=>$this->apiErrorMsg,"code"=>"119") );
		}
		
		$this->token=$result['token'];
		$this->password=$data['password'];
		//注册成功，自动登录
		$this->_loginAction($data['mobileNum'], $token=$this->_creatToken(), $result['expireIn'],I("post.channelID"));
		
		//$this->_returnJson(array("result"=>1,"accessToken"=>$result['token'],"expire"=>$result['expireIn']));
	}
	
	/**
	 *  手机重置登录密码操作
	 */
	public function resetPassword(){
	    $data=array(
	        "mobileNum"=>I("post.mobileNum"),
	        "smsCode"=>I("post.smsCode"),
	        "password"=>I("post.password")
	    );
	
	    if(!isNotEmptyArr($data)) $this->_returnJson(array("result"=>0,"info"=>"missing parameter","code"=>"123"));
	
	    $result=$this->_reSetPassword($data['mobileNum'],$data['password'],$data['smsCode']);
	
	    if (!$result) {
	        $this->_returnJson(array("result"=>0,"info"=>"api return error","errorMsg"=>$this->apiErrorMsg,"code"=>"119") );
	    }
	    
	    $this->_returnJson(array("result"=>1));
	    //dump($result);
	   /*  $this->token=$result['token'];
	    $this->password=$data['password'];
	
	    //注册成功，自动登录
	    $this->_loginAction($data['mobileNum'], $token=$this->_creatToken(), $result['expireIn']); */
	
	    //$this->_returnJson(array("result"=>1,"accessToken"=>$result['token'],"expire"=>$result['expireIn']));
	}
	
	public function test(){
		//$this->_loginAction('15989246851',$token,$expire);
	}
	
	/**
	 *  生成accessToken
	 */
	private function _creatToken(){
		return md5($this->token.time().rand(1000,9999));
	}
	
	
	
	/**
	 *  登录操作
	 */
	private function _loginAction($mobileNum,$token,$expire,$channelID=null){
		/* if (empty($expire)) {
			$expire=60*60*24*30;
		} */
		$expire=60*60*24*30;
		$expire_time=time()+$expire;
		
		//检测用户状态
		$user=D("User")->getUser($mobileNum);
		
		if (!$user) {
			
			$uid=D("User")->addUser($mobileNum,$this->token,$channelID);
			if($uid)
				$this->_sendUserInfo($mobileNum, date('Ymd H:i:s',time()));
		}
		else{
			$uid=$user['userID'];
				
			//是否冻结
			if ($user['isOn']==2) {
				$this->_returnJson(array("result"=>0,"info"=>"problem account","errorMsg"=>$user['errorMsg'],"code"=>"104"));
			}
		}
		
		S(C("CACHE_MEM"));
		
		$add_token=D("User")->addToken($token,json_encode(array("uid"=>$uid,"mobileNum"=>$mobileNum,"expireTime"=>$expire_time,"status"=>1,"errorMsg"=>null)),$expire);
		
		if (!$add_token) {
			$this->_returnJson(array("result"=>0,"info"=>"service busying","code"=>"105"),"json");
		}
		
		//获取旧token
		$old_token=D("User")->getOldToken($uid);
		
		if ($old_token) {
			//修改旧token的用户信息
			$add_token=D("User")->addToken($old_token,json_encode(array("uid"=>$uid,"mobileNum"=>$mobileNum,"expireTime"=>0,"status"=>0,"errorMsg"=>"你的账号已在另一台设备中登录了。")),86400);
		}
		
		//更新uid的token
		$reuslt=D("User")->editUserToken($uid,$token);
		
		//更新用户登录状态
		$update=D("User")->save(
		      array(
		          "userID"=>$uid,
		          "lastLogin"=>time(),
		          "lastIp"=>get_client_ip(),
		          "token"=>$this->token,
		          "accessToken"=>$token,
		          "password"=>$this->password,
		          "loginNum"=>$user['loginNum']+1
		      )
		 );
		
		//记录日志
		$update=D("UserLoginLog")->data(
		    array(
		        "userID"=>$uid,
		        "ip"=>get_client_ip(),
		        "addTime"=>time()
		    ))->add();
		
		
		$this->_returnJson(array("result"=>1,"accessToken"=>$token,'huitongToken'=>$this->token,"expire"=>$expire));
	}
	
	private function _sendUserInfo($mobile,$registerTime){
		$msgArray = array(
				'mobile'=>$mobile,
				'registerTime'=>$registerTime
		);
		$appKey = C('OIL_KEY');
		$signArray = array(
				$mobile,$registerTime,$appKey
		);
		
		sort($signArray,SORT_STRING);
		$str='';
		foreach ($signArray as $a){
			$str.=$a;
		}
		//dump($str);
		$signature=sha1($str);
		
		
		$send=array(
				'methodName'=>'receiveRegistInfo',
				'ver'=>'1.0',
				'appNo'=>C('OIL_APPNO'),
				'appKey'=>$appKey,
				'sign'=>$signature,
				'msg'=>$msgArray
		);

		//dump($send);
		//dump((json_encode($send)));
		$url=C('REGIST_URL');
		//dump($url);
		$result=http_post_json($url, json_encode($send));
		//dump($result);
		//$callback.=$result;
		if(!$result){
			$data=array(
				"mobile"=>$mobile,
				"registerTime"=>$registerTime,
				"msg"=>"接口出错",
				"addTime"=>time()
			);
			file_put_contents("payLog/regist_".date("Ymd")."txt", json_encode($data,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
			//return false;
		}else{
			$rt=json_decode($result,true);
			if ($rt['respCode']!='0000'){
				$data=array(
					"mobile"=>$mobile,
					"registerTime"=>$registerTime,
					"msg"=>"接口返回出错|".$rt['respMsg'],
					"addTime"=>time()
				);
				file_put_contents("payLog/regist_".date("Ymd")."txt", json_encode($data,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
				//return false;
			} else{
				$data=array(
					"mobile"=>$mobile,
					"registerTime"=>$registerTime,
					"msg"=>"发送成功|".$rt['respMsg'],
					"addTime"=>time()
				);
				file_put_contents("payLog/regist_".date("Ymd")."txt", json_encode($data,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
			}
		}
	}
		
	public function __destruct(){
		parent::__destruct();
	}
		
}
?>